﻿using System;
using System.Collections.Generic;
using System.Linq;
using Castle.Facilities.NHibernateIntegration;
using Castle.Services.Transaction;
using Iesi.Collections.Generic;
using NHATMSample.Models;
using NHibernate.Linq;

namespace NHATMSample.Service {
    [Transactional]
    public class TransactionalService {
        private readonly ISessionManager sessionManager;

        public TransactionalService(ISessionManager sessionManager) {
            this.sessionManager = sessionManager;
        }

        public virtual ICollection<Person> All() {
            using (var session = sessionManager.OpenSession()) {
                return session.Linq<Person>().ToList();
            }
        }

        [Transaction(TransactionMode.Requires)]
        public virtual void SaveNewFamily() {
            using (var session = sessionManager.OpenSession()) {
                var pepito = new Person {
                    Name = "Pepito",
                };
                session.Save(pepito);
                session.Save(new Person {
                    Name = "Pepe",
                    Children = new HashedSet<Person> {
                        pepito,
                    },
                });
            }
        }
    }
}